﻿using System;
using System.Linq.Expressions;
using System.Data.SqlClient;
using GSLMS.Core;
using System.Data.Objects;
using System.Data.EntityClient;
using System.Linq;

namespace GSLMS.Services
{
    public static class ObjectQueryExtension
    {
        public static int Delete<TEntity>(this ObjectQuery<TEntity> source, Expression<Func<TEntity, bool>> predicate)
                                                                where TEntity : class
        {
            try
            {
                var selectSql = (source.Where(predicate) as ObjectQuery).ToTraceString();
                int startIndex = selectSql.IndexOf(",");
                int endIndex = selectSql.IndexOf(".");
                string tableAlias = selectSql.Substring(startIndex + 1, endIndex - startIndex - 1);//get table alias
                startIndex = selectSql.IndexOf("FROM");
                string deleteSql = "DELETE " + tableAlias + " " + selectSql.Substring(startIndex);
                string connectionString = ((source as ObjectQuery).Context.Connection as EntityConnection).StoreConnection.ConnectionString;
                return ExecuteNonQuery(connectionString, deleteSql);
            }
            catch (Exception ex)
            {
                new Loger().ExceptionHand(ex);
                return -1;
            }

        }

        private static int ExecuteNonQuery(string connectionString, string sql, params SqlParameter[] parameters)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                SqlCommand cmd = conn.CreateCommand();
                cmd.Parameters.AddRange(parameters);
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.CommandText = sql;

                if (conn.State != System.Data.ConnectionState.Open)
                {
                    conn.Open();
                }
                return cmd.ExecuteNonQuery();
            }
        }
    }
}
